package gold.digger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by fanzhenyu02 on 2020/3/1.
 */
public class LC49 {

    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> res = new ArrayList<>();
        Map<String, List<String>> dict = new HashMap<>();
        for (String str : strs) {
            int[] letterMap = new int[26];
            for (int i = 0; i < str.length(); i++) {
                letterMap[str.charAt(i) - 'a']++;
            }

            String letterSum = letterMapToStr(letterMap);
            if (dict.containsKey(letterSum)) {
                List<String> dictList = dict.get(letterSum);
                dictList.add(str);
            } else {
                List<String> dictList = new ArrayList<>();
                dictList.add(str);
                dict.put(letterSum, dictList);
            }
        }

        for (Map.Entry<String, List<String>> entry : dict.entrySet()) {
            res.add(entry.getValue());
        }

        return res;
    }

    String letterMapToStr(int[] letterMap) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < letterMap.length; i++) {
            if (letterMap[i] > 0) {
                sb.append(letterMap[i] + String.valueOf((char) ('a' + i)));
            }
        }
        return sb.toString();
    }


    public static void main(String[] args) {
        LC49 an = new LC49();
        String[] input = {"bur", "rub"};

        System.out.println(an.groupAnagrams(input));
    }
}
